package com.sy.core.upload;


import com.sy.core.util.BaseUUID;
import com.sy.core.util.RestResult;
import com.sy.core.web.BaseCtl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文件上传控制器
 *
 * @author Chong.caixin
 */
@Controller
@RequestMapping("upload")
public class UploadCtl extends BaseCtl {

    protected final Logger logger = LoggerFactory.getLogger(UploadCtl.class);
    @Autowired
    UploadConfig uploadConfig;


    /**
     * <font color='red'>文件上传控制</font><br>
     *
     * @Description:<br>
     * @Title: imageUpload<br>
     * @Package com.jobo.core.web<br>
     * @author Chong.caixin<br>
     * @date 2018年9月11日<br>
     * @version V2.0<br>
     */
    @RequestMapping(value = "fileUpload")
    @ResponseBody
    public RestResult imageUpload(@RequestParam("file") MultipartFile[] file, String orderPk,
                                  HttpServletRequest request, HttpServletResponse response) {
        // JS跨域参数准备
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,OPTIONS");
        response.setHeader("Access-Control-Allow-Credentials ", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
        /*if (StringUtils.isBlank(orderPk)) {
            return new RestResult("691", "参数异常,合同信息不存在");
        }*/
        // 判断系统类型 是window 还是 linux
        String uploadPrefix = "";
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            uploadPrefix = uploadConfig.getUploadPath();
        } else {
            uploadPrefix = uploadConfig.getUploadPathForLinux();
        }
        // 上传成功后，返回文件记录
        List<String> trinfo = new ArrayList<String>();
        for (MultipartFile file1 : file) {
            String str = null;
            String OriginalFilename;
            if (!file1.isEmpty()) {
                OriginalFilename = file1.getOriginalFilename();
                //str = OriginalFilename.substring(OriginalFilename .lastIndexOf("."));
                if (!file1.isEmpty()) {
                    //OriginalFilename = UUID.randomUUID().toString() .replace("-", "") + str;
                    // 定义文件夹生成规范 按天 按时间
                    String sr = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
                    String path = uploadPrefix + "//" + "//" + sr;
                    try {
                        // 创建文件
                        File fileDir = new File(path);
                        // 如果文件夹不存在则创建
                        if (!fileDir.exists() && !fileDir.isDirectory()) {
                            fileDir.mkdirs();
                        }
                        // 保存文件
                        String src = path + "//" + OriginalFilename;
                        File saveFile = new File(src);
                        file1.transferTo(saveFile);

                        // 图片存放地址
                        String orign = "/" + sr + "/" + OriginalFilename;
                        String urlprefix = uploadConfig.getUploadPrefix();
                        orign = urlprefix + "/files/" + orign;
                        logger.info("File Upload is successs! The Path is..........:" + orign);
                        trinfo.add(orign);
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                        return new RestResult("691", "文件上传失败");
                    }
                }
            } else {
                return new RestResult("691", "非法请求,参数类型不正确");
            }
            return new RestResult("200", "文件上传成功", trinfo);
        }
        return new RestResult("691", "文件信息为空", trinfo);
    }

}

